package de.luisoft.util;

import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import de.luisoft.dto.WahlDTO;


public class SendMail {

	private static final Logger log = Logger.getLogger(SendMail.class.getName()); 

	public void send(WahlDTO w, long key) throws Exception {
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("lui.baeumer@googlemail.com", "Fathi Sanhaji"));
            msg.setReplyTo(new Address[] {new InternetAddress("fathi@gmx.de", "Fathi Sanhaji")});
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(w.getEmail(), w.getVorname() + " " + w.getName()));
            msg.addRecipient(Message.RecipientType.BCC,
            				 new InternetAddress("lui.baeumer@googlemail.com", "Lui"));
            msg.setSubject(w.getVorname() + ", deine @ugustinianum-Projektwahl");
            
            StringBuffer strb =new StringBuffer();
            strb.append("Hallo " + w.getVorname() + ",\n\n");
            strb.append("du hast deine Projekte in der folgenden Reihenfolge gewählt:\n\n");
            int i = 1;
            if (w.getSelect() != null) {
	            for (String p : w.getSelect()) {
	            	strb.append(i + ". " + p + "\n");
	            	i++;
	            }
            }
            strb.append("\n");
            strb.append("Klasse: " + w.getKlasse() + "\n");
            strb.append("Dein @ugustinianum");
            strb.append("\n");
            strb.append("\n");
            strb.append("Bitte klicke den Link an, um die Angaben zu bestätigen:\n");
            strb.append("http://augustinianum-projekt.appspot.com/register?id=" + key);
            
            msg.setText(strb.toString());
            Transport.send(msg);

            log.info("Send mail with key " + key + " to " + w.getEmail());
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
	}
}
